﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class ConnectionHelper
    {
        public static string GetSqlConnectionString()
        {
            const string StrSqlConnection = "Data Source=127.0.0.1;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=123456";
            return StrSqlConnection;
        }

        public static SqlConnection GetConnection() 
        {
            SqlConnection connection = new SqlConnection(GetSqlConnectionString());
            TryOpenConnection(ref connection);
            return connection;
        }

        public static SqlConnection GetConnection(string connectionString)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            TryOpenConnection(ref connection);
            return connection;
        }

        public static void TryOpenConnection(ref SqlConnection conn)
        {
            try
            {
                if(conn.State==ConnectionState.Closed) conn.Open();
            }
            catch (Exception)
            {
                throw;
            }
            finally 
            {
                conn.Close(); 
            }
        }

    }
}
